
package com.tools.cleanmaster.controller;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;

import com.tools.cleanmaster.common.thread.ThreadPool;
import com.tools.cleanmaster.model.TrashType;
import com.tools.cleanmaster.model.item.TrashItem;
import com.tools.cleanmaster.utils.LogHelper;
import com.tools.cleanmaster.utils.StorageUtils;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class AppCacheScanner extends TrashScanner {
    private static final int THREAD_COUNT = 2;

    public AppCacheScanner(Context context, TrashHandler handler) {
        super(context, handler);
    }

    @Override
    public void scan(int progress) {
        mIsScanning = true;
        // Debug.startMethodTracing("trash_cache", 200 * 1024 * 1024);
        doScan(progress);
        // Debug.stopMethodTracing();
        mIsScanning = false;
    }

    private long doScan(final int totalIncreaseProgress) {
        long startTime = System.currentTimeMillis();
        if (mStopRequested) {
            return 0;
        }
        final PackageManager pm = mContext.getPackageManager();
        final List<ApplicationInfo> installedApps = pm.getInstalledApplications(0);
        final long[] totalSize = new long[1];
        final int N = installedApps == null ? 0 : installedApps.size();
        if (N == 0) {
            mTrashHandler.updateProgress(totalIncreaseProgress, null);
        }

        //系统缓冲为0的App包名列表。
        final AtomicInteger index = new AtomicInteger(0);
        final Object lock = new Object();
        final CountDownLatch latch = new CountDownLatch(THREAD_COUNT);
        for (int i = 0; i < THREAD_COUNT; i++) {
            ThreadPool.runOnPool(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        if (mStopRequested) {
                            break;
                        }
                        int i = index.getAndIncrement();
                        if (i >= N) {
                            break;
                        }
                        ApplicationInfo appInfo = installedApps.get(i);
                        /*if (CleanConstant.PSAFE_FILTER && TextUtils.equals(CleanConstant.PSAFE_PKGNAME, appInfo.packageName)) {
                            continue;
                        }*/
                        int progress = calculateProgress(totalIncreaseProgress, i, N);
                        String appName = appInfo.loadLabel(pm).toString();
                        mTrashHandler.updateProgress(progress, appName);
                        String packageName = appInfo.packageName;
                        if (PKGS_WHITE_LIST.contains(packageName)) {
                            continue;
                        }
                        // 因为目前清除系统缓存都是跳到系统设置界面，因此hasSystemPerm一律传入true，以便加上外置系统缓存值
                        long appCacheSize = StorageUtils.getAppCacheSize(mContext, packageName,
                                /* hasSystemPerm */true);
                        if (mStopRequested) {
                            break;
                        }

                        synchronized(lock) {
                            if (appCacheSize < 0) {
                                continue;
                            }
                            if (appCacheSize == 0) {
                                continue;
                            } else {
                                TrashItem trash = new TrashItem();
                                trash.trashType = TrashType.APP_CACHE;
                                trash.pkgName = appInfo.packageName;
                                trash.appName = appName;
                                trash.filePath = appInfo.sourceDir;
                                trash.size = appCacheSize;
                                mTrashesData.putTrash(TrashType.APP_CACHE, trash);
                                totalSize[0] += appCacheSize;
                            }
                        }
                    }
                    latch.countDown();
                }
            });
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
        }
        if (mStopRequested) {
            return totalSize[0];
        }
        //猜测 latch.await()可能异常，等待失败。通过改变标记量，让工作线程退出。
        mStopRequested = true;
        mTrashHandler.onTrashTypeFinish(TrashType.APP_CACHE, totalSize[0]);
            LogHelper.i(SUB_TAG, "系统缓存扫描耗时=" + (System.currentTimeMillis() - startTime) + "毫秒");
        return totalSize[0];
    }

    /**
     * 删除所有系统缓存
     *
     * @param cxt
     */
    public static void clearAllAppCaches(Context cxt) {
        StorageUtils.clearAllAppCachesOneKey(cxt);
    }

    public static long getAppCacheSize(Context cxt, String pkgName) {
        // 因为目前清除系统缓存都是跳到系统设置界面，因此hasSystemPerm一律传入true，以便加上外置系统缓存值
        return StorageUtils.getAppCacheSize(cxt, pkgName, true);
    }
}
